'use strict'

const { defineConfig } = require('@vue/cli-service')
const webpack = require('webpack')
const port = process.env.port || process.env.npm_config_port || 8000
const fs = require('fs')

module.exports = defineConfig({
  publicPath: './',
  outputDir: 'dist',
  assetsDir: 'static',
  transpileDependencies: true,
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    client: {
      overlay: false
    },
    compress: false, // 如果有sse类型的流式接口，webflux服务，需要关闭这个，否则接口会代理不成功，会一直挂起等待中
    port: port,
    // open: true,//启动时打开默认游览器，可能会调用运行或cmd命令窗口打开游览器，如果安装了360，可能会被拦截
    proxy: {
      '/server_data': {
        target: 'https://127.0.0.1:443/server_data',
        // target: 'https://hl0109.cn/server_data',
        ws: true, // 代理websockets
        changeOrigin: true, // 虚拟托管站点
        secure: false, // 如果是https接口，需要配置这个参数为true
        headers: {
          'Cache-Control': 'no-cache'
        },
        pathRewrite: {
          ['^' + '/server_data']: ''
        }
      }
    }
  },
  configureWebpack: {
    plugins: [
      {
        apply(compiler) {
          // 在编译阶段处理资源
          compiler.hooks.compilation.tap('GlobalStringReplacePlugin', (compilation) => {
            // 处理每个模块的资源
            compilation.hooks.processAssets.tap({ name: 'GlobalStringReplacePlugin', stage: compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS }, (assets) => {
              for (const assetName in assets) {
                let newSource = assets[assetName].source()
                if (newSource && newSource.includes && newSource.includes('CONFIG_WEBPACK_FILE_LIST_BASE64')) {
                  newSource = newSource.replace('CONFIG_WEBPACK_FILE_LIST_BASE64', getFileListBase64())
                  compilation.updateAsset(assetName, new webpack.sources.RawSource(newSource))
                }
              }
            }
            )
          })
        }
      }
    ]
  }
})

/** ------------------------------------------------------------------------------------------------------------------------------------*/
/** 获取当前系统src下的文件信息，以及解析@fileInfo{json数据}@fileInfo包裹起来的文件信息，生成对应结构数据注入到页面全局变量中，用于动态生成路由，项目文件管理等**/
function getFileListBase64() {
  const fileList = getWebSysFileData('/src')
  return Buffer.from(encodeURIComponent(JSON.stringify(fileList))).toString('base64')
}
function getWebSysFileData(path) {
  const root = __dirname
  const files = fs.readdirSync(root + path)
  return files.map(filename => {
    const fullPath = root + path + '/' + filename
    const isDirectory = fs.statSync(fullPath).isDirectory()
    const fileData = {
      filename: filename,
      filepath: path + '/' + filename,
      isDirectory: isDirectory
    }
    if (!isDirectory) {
      if (filename.endsWith('.vue')) {
        const fileText = fs.readFileSync(fullPath, { encoding: 'utf8' }).toString()
        if (fileText.includes('@fileInfo') && fileText.includes('fileInfo@')) {
          const fileInfoText = fileText.substring(fileText.indexOf('@fileInfo') + 9, fileText.indexOf('fileInfo@'))
          fileData.meta_str = fileInfoText
          if (fileInfoText !== '') {
            try {
              fileData.meta = (new Function('return ' + fileInfoText))()
            } catch (e) {
              console.log('代码文件中的@fileInfo{值}fileInfo@解析失败', fullPath, e)
            }
          }
        }
      }
    } else {
      fileData.children = getWebSysFileData(fileData.filepath)
    }
    return fileData
  })
}
/** ------------------------------------------------------------------------------------------------------------------------------------*/
